package com.market.cash.ui.presenter

import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.view.ICashRootOrderDetailsView
import com.market.cash.utils.helper.CashRootCommentDialogHelper
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.CashRootStatusHelper
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/28 13:45
 * @Annotation：贷款详情 Presenter 实现
 */
class CashRootOrderDetailsPresenter(private val iView: ICashRootOrderDetailsView) : ProPresenter(iView) {

    /**
     * 获取贷款状态信息
     */
    fun loadCashRootOrderStatusAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_PROCESS_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_PROCESS_PATH)
            put("product",iView.loadPName())
            put("token",iView.loadPToken())
        }
        doCashRootPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {

                    //申请状态
                    val applyStatus = obj.optString("applyStatus","")
                    //订单状态
                    val orderStatus = obj.optString("orderStatus","")

                    val isReviewing = CashRootStatusHelper.StatusRepository(applyStatus,orderStatus).isReviewing()
                    val isDisbursing = CashRootStatusHelper.StatusRepository(applyStatus,orderStatus).isDisbursing()
                    val isRejected = CashRootStatusHelper.StatusRepository(applyStatus,orderStatus).isRejected()
                    val isRepay = CashRootStatusHelper.StatusRepository(applyStatus,orderStatus).isRepayNow()

                    //审核中
                    if (isReviewing){
                        obj.put("eventRemark", "LoanAudit Page")
                        iView.showCashRootOrderAuditViews(obj)
                        return
                    }

                    //放款中
                    if (isDisbursing){
                        obj.put("eventRemark", "LoanLending Page")
                        iView.showCashRootOrderLendingViews(obj)
                        return
                    }

                    //已拒绝
                    if (isRejected){
                        obj.put("eventRemark", "LoanRejected Page")
                        iView.showCashRootOrderRejectedViews(obj)
                        return
                    }

                    //待还款
                    iView.hideCashRootLoading()
                    iView.showCashRootOrderRepayViews(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                loadCashRootOrderDetailsAction()
            }
        })
    }

    /**
     * 获取贷款信息
     */
    private fun loadCashRootOrderDetailsAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_LOAN_APPLY_PATH)
            put("product",iView.loadPName())
            put("token",iView.loadPToken())
        }
        doCashRootPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //显示共用View
                    iView.showCashRootOrderCommonViews(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }

    /**
     * 获取账户列表
     */
    fun loadCashRootBindCardListAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CASHROOT_API_ACCOUNT_LIST_PATH)
        }
        doCashRootPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                val accountList = arrayListOf<JSONObject>()

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("isEdit", false)
                        accountList.add(item)
                    }
                }
                iView.showCashRootBindCardList(accountList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }

    /**
     * 只有审核中或放款中需要调此接口
     * 获取评分配置
     */
    fun loadCashRootScoreCommentAction() {
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CASHROOT_API_STAR_COMMENT_PATH)
        }
        doCashRootPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    CashRootCommentDialogHelper.showStarDialog(iView.getContext()!!,obj,true)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitCashRootBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        iView.showCashRootLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CASHROOT_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }
        doCashRootPostAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadCashRootBindCardListAction()

                val obj = data.optJSONObject("obj") ?: JSONObject()
                // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                val addBindFlag = obj.optString("addBindFlag")
                if (addBindFlag == "YES") {
                    //需要提示绑定另一个渠道账户
                    var otherAccountInfo: JSONObject? = null

                    //用于从APP配置中获取（walletChannels）对应的信息
                    val channel = obj.optString("channel")
                    if (channel.isNotBlank()) {
                        val customize = CashRootCustomConfigsHelper.getCashRootConfigData()
                        if (customize != null) {
                            val walletChannels = customize.optJSONArray("walletChannels")
                            if (walletChannels != null && walletChannels.length() > 0) {
                                for (i in 0..<walletChannels.length()) {
                                    val item = walletChannels.optJSONObject(i)
                                    if (channel == item.optString("value")) {
                                        otherAccountInfo = item
                                        break
                                    }
                                }
                            }

                            // 只有非空的情况下才处理
                            if (otherAccountInfo != null) {
                                otherAccountInfo.put("walletMobile", mobile)
                                //提示绑定另一个渠道账户
                                iView.showCashRootBindCardOtherDialog(otherAccountInfo)
                                return
                            }
                        }
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteCashRootAccountAction(ids: String) {
        iView.showCashRootLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CASHROOT_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        doCashRootPostAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                iView.showCashRootToast(data.optString("msg"))
                //刷新列表
                loadCashRootBindCardListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }
}